<!-- 添加商品的信息 -->
<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 头部的提示信息 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 状态条 -->
      <el-steps
        :space="200"
        :active="active-0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 el-form必须包含在外面，因为el-tabs和pane必须连在一起-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="ruleFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          style="height: 100%;"
          v-model="active"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane
            label="基本信息"
            name="0"
          >
            <el-form-item
              class="title"
              label="商品分类"
              prop="goods_cat"
            >
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item
              class="title"
              label="商品名称"
              prop="goods_name"
            >
              <el-input
                v-model="addForm.goods_name"
                type="text"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="title"
              label="商品价格"
              prop="goods_price"
            >
              <el-input
                v-model="addForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="title"
              label="商品数量"
              prop="goods_number"
            >
              <el-input
                v-model="addForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="title"
              label="商品重量"
              prop="goods_weight"
            >
              <el-input
                v-model="addForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品参数"
            name="1"
          >
            <el-form-item
              class="title"
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item2,index) in item.attr_vals"
                  :key="index"
                  :label="item2"
                  border
                  style="margin-right: 5px"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品属性"
            name="2"
          >
            <el-form-item
              class="title"
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
              prop=""
            >
              <el-input
                v-model="item.attr_vals"
                type="text"
              ></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品图片"
            name="3"
          >
            <el-upload
              :action="UpUrl"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane
            label="商品内容"
            name="4"
          >
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button
              type="primary"
              class="addBtn"
              @click="addGoods"
            >添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片的dialog -->
    <el-dialog
      title="预览图片"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
      <el-image
        style="width: 100%; height: 100%"
        :src="previewImgUrl"
      ></el-image>
      <span
        slot="footer"
        class="dialog-footer"
      >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: "0",
      UpUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      headers: { Authorization: window.sessionStorage.getItem("token") },
      // 预览图片的路径
      previewImgUrl: "",
      // 控制预览图片对话框
      previewDialogVisible: false,
      addForm: {
        goods_name: "",
        goods_price: null,
        goods_number: null,
        goods_weight: null,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      cateList: [],
      manyTableData: [],
      onlyTableData: [],
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCategories();
  },
  methods: {
    async getCategories() {
      const { data: res } = await this.$http.get("categories");
      this.cateList = res.data;
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return this.$message.error("请选择三级分类");
      }
    },
    // 在切换tabs前校验
    beforeTabLeave(activeName, oldActibeName) {
      if (oldActibeName === "0" && this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        this.$message.error("请选择三级分类");
        return false;
      }
    },
    async tabClicked() {
      if (this.active === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取商品参数失败");
        this.manyTableData = res.data;
        this.manyTableData.forEach((item) => {
          item.attr_vals = item.attr_vals.split(" ");
        });
      } else if (this.active === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取商品参数失败");
        this.onlyTableData = res.data;
        console.log(this.onlyTableData);
      }
    },
    // 预览图片
    handlePreview(file) {
      this.previewImgUrl = file.response.data.url;
      this.previewDialogVisible = true;
      console.log(this.previewImgUrl);
    },
    handleRemove(file) {
      this.addForm.pics = this.addForm.pics.filter((item) => {
        return item.pic !== file.response.data.tmp_path;
      });
    },
    // 上传图片成功后触发的事件
    handleSuccess(response) {
      const picsInfo = {
        pic: response.data.tmp_path,
      };
      console.log(picsInfo);
      this.addForm.pics.push(picsInfo);
      console.log(this.addForm);
    },
    // 添加商品的按钮事件
    addGoods() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的信息");
        let a = this.addForm.goods_cat.toString();
        this.addForm.goods_cat = a;
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        const { data: res } = await this.$http.post("goods", this.addForm);
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
      });
    },
  },
};
</script>

<style  scoped>
.title {
  text-align: left;
}

.addBtn {
  margin-top: 10px;
}
</style>
